package com.morgan.storageperlib

import android.Manifest
import android.content.Intent
import android.os.Build
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.permissionx.guolindev.PermissionX
import com.permissionx.guolindev.callback.ExplainReasonCallbackWithBeforeParam
import com.permissionx.guolindev.callback.ForwardToSettingsCallback
import com.permissionx.guolindev.callback.RequestCallback
import java.lang.ref.WeakReference


/**
 *description：外部存储权限申请适配 https://www.jianshu.com/p/d5573e312bb8
 * 必须在activity或者Fragment的onCreate中初始化
 *<br>author：caowugao
 *<br>time：2021/3/12 0012 16:34
 */
class ExternalStoragePerRequestCompat(act : AppCompatActivity, contract : ActivityResultContract<Intent, ActivityResult> = ActivityResultContracts.StartActivityForResult()) {
    private val actRef = WeakReference<AppCompatActivity>(act)
    private var mResultCallback : RequestCallback? = null
    private val androidRHandler = ExternalStorageForRHandler(act, contract) {success ->
        mResultCallback?.let {callback ->
            val pers = mutableListOf<String>(Manifest.permission.MANAGE_EXTERNAL_STORAGE)
            callback.onResult(success, if (success) pers else mutableListOf(), if (!success) pers else mutableListOf())
        }
    }
        /**
         *
         */
        fun request(beforeRequest : ExplainReasonCallbackWithBeforeParam, afterRequestNeverDenied : ForwardToSettingsCallback, resultCallback : RequestCallback) {
            //https://blog.csdn.net/guolin_blog/article/details/106181780/
            if (Build.VERSION.SDK_INT >= 30) {//android R(即android 10+)以上需要通过intent跳转到权限管理界面 <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
                mResultCallback = resultCallback
                androidRHandler.launch()
                return
            }
            val act = actRef.get() ?: return
            val list = mutableListOf<String>(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
            PermissionX.init(act).permissions(list)
                    .explainReasonBeforeRequest()
                    .onExplainRequestReason(beforeRequest)
                    .onForwardToSettings(afterRequestNeverDenied)
                    .request(resultCallback)
        }
}